from   machine import UART
import struct
import myconfig
import machine
import mymqtt
import gc,_thread
import utime
import wifi_connect

modbus_addr = 10            #modbus 地址
modbus_data = [0]*100       #modbus 寄存器
modbus_data_back = [0]*100

#小端模式(低字节在前)
modbus_data[0] = 0  # 光电数
modbus_data[1] = 0  
modbus_data[2] = 0  # 剔除数
modbus_data[3] = 0
modbus_data[4] = 0  # 检测速度
modbus_data[5] = 0  
modbus_data[6] = 0     # IO状态 0：关机 1：红 2：绿 3：黄 4:蜂鸣器
modbus_data[7] = 1000  # 温度
modbus_data[8] = 0  #  
modbus_data[9] = 0  #  

#检测modbus数据是否更新
def check_data_updata():
    b_updata = False
    for i in range(0,20):
        if modbus_data[i] != modbus_data_back[i] :
            b_updata = True
        modbus_data_back[i] = modbus_data[i]  
    return  b_updata      

table_crc_hi = (
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
    0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
    0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
    0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
    0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
    0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
    0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
    0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
    0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
    0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
    0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
    0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
    0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
    0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
    0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
    0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
    0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
    0x80, 0x41, 0x00, 0xC1, 0x81, 0x40)

table_crc_lo = (
    0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06,
    0x07, 0xC7, 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD,
    0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09,
    0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A,
    0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, 0x14, 0xD4,
    0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,
    0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3,
    0xF2, 0x32, 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4,
    0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A,
    0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29,
    0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED,
    0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26,
    0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60,
    0x61, 0xA1, 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67,
    0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F,
    0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68,
    0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, 0xBE, 0x7E,
    0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5,
    0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71,
    0x70, 0xB0, 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92,
    0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C,
    0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B,
    0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89, 0x4B, 0x8B,
    0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,
    0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42,
    0x43, 0x83, 0x41, 0x81, 0x80, 0x40)

#crc 校验
def calculate_crc16(data, data_len):
    crc_hi = crc_lo = 0xFF
    for i in range(data_len):
        index = crc_lo ^ data[i]
        crc_lo = crc_hi ^ table_crc_hi[index]
        crc_hi = table_crc_lo[index]

    result = crc_hi << 8 | crc_lo
    return struct.pack('<H',result)

#串口读数据
def uart_read_bytes():
    try:
        if uart.any():
            return True,uart.read() 
        else:
            return False,b'0'
    except Exception:
        pass

#串口写数据
def uart_send_bytes(bytes,crlf = True):
    try:       
        if(crlf):
            uart.write(bytes+"\r\n")
        else:
            uart.write(bytes)
    except Exception:
        pass    


# 数据接收 crc 校验
def check_crc(data):

    list_data = list(data)
    len_data  = len(list_data) 

    crc_cal =calculate_crc16(list_data, len_data-2)

    if (crc_cal[0] == list_data[len_data-2]) and (crc_cal[1] == list_data[len_data-1]):
        return True
    else:
        return False

# 0X03功能码 读寄存器
def fun_03(data):
    
    start_addr = data[2]<<8 | data[3]
    num_read   = data[4]<<8 | data[5]

    #地址限制
    if start_addr + num_read >= 100 :
        list_error_back = bytearray()
        list_error_back.append(data[0])
        list_error_back.append(0x83)
        uart_send_bytes(list_error_back)
        return 
     
    #读取数据
    list_data_read = []
    for i in range(num_read):
        list_data_read.append(modbus_data[start_addr+i]) 
    
    #数据返回
    list_send_back = bytearray()
    list_send_back.append(data[0]) #地址
    list_send_back.append(data[1]) #功能码
    list_send_back.append(len(list_data_read)*2) #读取的字节数

    #添加数据
    for item in list_data_read:
        list_send_back.append(item>>8)    #H
        list_send_back.append(item&0xFF)  #L

    #crc 校验
    crc = calculate_crc16(list_send_back,len(list_send_back))
    list_send_back.append(crc[0])
    list_send_back.append(crc[1])

    #返回数据
    uart_send_bytes(list_send_back)

# 0X10功能码 写寄存器
def fun_10(data):

    start_addr = data[2]<<8 | data[3]  #开始地址
    num_write  = data[4]<<8 | data[5]  #写寄存器个数
    num_bytes  = data[6]               #写寄存器字节数

    #地址限制
    if start_addr + num_write >= 100 :
        list_error_back = bytearray()
        list_error_back.append(data[0])
        list_error_back.append(0x90)
        uart_send_bytes(list_error_back)
        return
     
    #保存数据
    for i in range(num_write):
        data_write = data[7+2*i]<<8 | data[8+2*i]
        modbus_data[start_addr+i]  = data_write
    
    list_send_back = bytearray()
    list_send_back.append(data[0])  #设备#地址
    list_send_back.append(data[1])  #功能码
    list_send_back.append(data[2])  #开始地址
    list_send_back.append(data[3])  #开始地址
    list_send_back.append(data[4])  #写寄存器个数
    list_send_back.append(data[5])  #写寄存器个数

    #crc 校验
    crc = calculate_crc16(list_send_back,len(list_send_back))
    list_send_back.append(crc[0])
    list_send_back.append(crc[1])

    #返回数据
    uart_send_bytes(list_send_back)


#普通串口数据
#485参数配置
#name:value   
def uart_del(data):

    try:
        data_str = data.decode()  

        #设置wifi
        if data_str.find("get_wifi_name") != -1:
            uart_send_bytes("wifi_name:"+myconfig.wifi_name)
        elif data_str.find("set_wifi_name") != -1:
            myconfig.wifi_name = data_str.split(':')[1]
            uart_send_bytes("wifi_name:"+myconfig.wifi_name)
        
        elif data_str.find("get_wifi_psw") != -1:
            uart_send_bytes("wifi_psw:"+myconfig.wifi_psw)
        elif data_str.find("set_wifi_psw") != -1:
            myconfig.wifi_psw = data_str.split(':')[1]
            uart_send_bytes("wifi_psw:"+myconfig.wifi_psw)

        elif data_str.find("set_devic_id") != -1:
            # myconfig.devic_id = data_str.split(':')[1]
            # uart_send_bytes("devic_id:"+myconfig.devic_id)  
            pass  
        elif data_str.find("get_devic_id") != -1:
            uart_send_bytes("devic_id:"+myconfig.devic_id)   

        elif data_str.find("get_mqtt_name") != -1:
            uart_send_bytes("mqtt_name:"+myconfig.mqtt_name)   
        elif data_str.find("set_mqtt_name") != -1:
            myconfig.mqtt_name = data_str.split(':')[1]
            uart_send_bytes("mqtt_name:"+myconfig.mqtt_name)   

        elif data_str.find("get_mqtt_passwd") != -1:
            uart_send_bytes("mqtt_passwd:"+myconfig.mqtt_passwd)    
        elif data_str.find("set_mqtt_passwd1") != -1:
            myconfig.mqtt_passwd = data_str.split(':')[1]
        elif data_str.find("set_mqtt_passwd2") != -1:
            myconfig.mqtt_passwd = myconfig.mqtt_passwd + data_str.split(':')[1]
        
        elif data_str.find("get_mqtt_client_id") != -1:
            uart_send_bytes("mqtt_client_id:"+myconfig.client_id)    
        elif data_str.find("set_mqtt_client_id") != -1:
            myconfig.client_id = data_str.split(':')[1]
            uart_send_bytes("mqtt_client_id:"+myconfig.client_id)  

        elif data_str.find("get_mserver") != -1:
            uart_send_bytes("mserver:"+myconfig.mserver) 
        elif data_str.find("set_mserver") != -1:
            myconfig.mserver = data_str.split(':')[1]
            uart_send_bytes("set_mserver:"+myconfig.mserver) 

        elif data_str.find("get_port") != -1:
            uart_send_bytes("port:"+str(myconfig.port)) 
        elif data_str.find("set_port") != -1:
            myconfig.port = int(data_str.split(':')[1])
            uart_send_bytes("port:"+myconfig.port)

        elif data_str.find("save_config") != -1:
            myconfig.save_config()
        
        elif data_str.find("reboot") != -1:
            machine.reset()     

        elif data_str.find("get_error_code") != -1:
            uart_send_bytes("error_code:"+str(myconfig.error_code))  

        elif data_str.find("get_error_str") != -1:
            uart_send_bytes("error_str:"+myconfig.error_str)

        elif data_str.find("get_version") != -1:
            uart_send_bytes("version:"+myconfig.version)

        elif data_str.find("updata") != -1:
            mymqtt.b_check_updata = True                 

        elif data_str.find("get_run_status") != -1:
            uart_send_bytes("run_status:"+myconfig.run_status)   

        elif data_str.find("get_type_net") != -1:
            uart_send_bytes("type_net:"+str(myconfig.type_net)) 

        elif data_str.find("set_type_net") != -1:
            myconfig.type_net = int(data_str.split(':')[1])
            uart_send_bytes("type_net:"+str(myconfig.type_net))  
        
        #获取RAM
        elif data_str.find("get_mem_free") != -1:    
            uart_send_bytes("mem_free:"+str(gc.mem_free()))  

        #关闭4g模块
        elif data_str.find("disable_cat1") != -1:    
            print("AT+CPOWD=1") 

        #获取4G信号
        elif data_str.find("get_4G_signal") != -1:    
            uart_send_bytes("4G_signal:"+str(mymqtt.csq))  

    except Exception as e:
        uart_send_bytes(e)

#modbus 入口
def RS485_LOOP():
    while True:
        res, data = uart_read_bytes()
        if res:
            #modbus协议
            if check_crc(data) == True: 
                if data[0] == modbus_addr:  
                    # 03 功能码
                    if data[1] == 3:
                        fun_03(data) 
                    # 10 功能码
                    if data[1] == 16:
                        fun_10(data) 
            else:
                #自定义协议
                uart_del(data)  
            gc.collect()
        utime.sleep_ms(1)

#485串口设备
uart =  UART(1, baudrate=9600, rx=32,tx=33,timeout=5)

#串口读取线程
_thread.start_new_thread(RS485_LOOP, ())

